package com.ht.api.call.func.impl.kf;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.exception.HtException;
import com.ht.api.open.OpenUtil;
import com.ht.api.service.WwxService;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 修改客服账号
 * @author asq
 * @createTime 2025年3月9日 09:11:00
 */
public class KfAccountEditFunctionCall implements IFunctionCall {
	/** 接口ID：修改客服账号 */
	private static final long API_ID = 1891360374658306048L;

	@Override
	public String getName() {
		return "修改客服账号";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		Entity oldAccount = Db.createSqlParser("kf_account").select("appid, open_kfid,name,avatar")
				.findById(me.getDataSource(), param.getStr("main_id"));
		String appId = oldAccount.getStr("appid");

		if (param.getStr("name").equals(oldAccount.getStr("name")) && param.getStr("avatar").equals(oldAccount.getStr("avatar"))) {
			return null;//没有更改的信息，则不用做任何处理
		}

		// 请求平台接口创建账号
		JSONObject accountParam = JSONUtil.createObj();
		accountParam.set("open_kfid", oldAccount.getStr("open_kfid"));

		if (!param.getStr("avatar").equals(oldAccount.getStr("avatar"))) {
			// 获取头像的媒体ID
			String imageMediaId = WwxService.getTempImageMediaId(appId, param.getStr("avatar"));
			accountParam.set("media_id", imageMediaId);
		}

		if (!param.getStr("name").equals(oldAccount.getStr("name"))) {
			accountParam.set("name", param.getStr("name"));
		}

		String str = OpenUtil.call(appId, API_ID, accountParam);

		// 如果企微接口调用成功，则操作本地数据库
		JSONObject obj = JSONUtil.parseObj(str);
		if (obj.getInt("errcode") != 0) {
			throw new HtException("企微接口返回错误：" + obj.getStr("errmsg"));
		}
		
		return JSONUtil.createObj();
	}


}
